//
//  MVController.m
//  Gegeda_music_MY
//
//  Created by lanou3g on 15/11/5.
//  Copyright © 2015年 周莹. All rights reserved.
//

#import "MVController.h"
#import "MVCollectionViewCell.h"
#import "MVModel.h"
#import "MJExtension.h"
#import "UIImageView+WebCache.h"
#import <MediaPlayer/MediaPlayer.h>
//#import <AVKit/AVKit.h>


#define Url @"http://spark.api.xiami.com/api?api_key=263b63d85992a30cc6030aff03c9dfd0&call_id=1446690824877&av=android_105&v=5.0&app_v=5030200&os_v=19_4.4.4&ch=702006&network=1&device_id=867822024649849&platform_id=1&gps=0.0%2C0.0&lg=1&utdid=VYZVPTIG4FIDADl%2BMJXO9h3A&resolution=1280*720&method=mv.music-list&order=recommend&page=1&limit=20&new=1&language=0&gender=0&tag=0&proxy=0&api_sig=717fb4383035e37013d1961f5870e8d9"

@interface MVController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>


@property (strong, nonatomic) IBOutlet UICollectionView *MVCollectionView;

//解析数据
@property(nonatomic, strong)NSMutableArray *dataArray;

@property(nonatomic,strong)MPMoviePlayerViewController *moviePlayerViewController;

@property(nonatomic,strong)NSString *urlStr;

@end

@implementation MVController

#pragma mark - 懒加载
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UICollectionView *)MVCollectionView{
    if (!_MVCollectionView) {
        _MVCollectionView = [[UICollectionView alloc] init];
    }
    return _MVCollectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [[UIColor alloc] initWithRed:255.0/255 green:222.0/255 blue:249.0/255 alpha:1.0];
    self.MVCollectionView.delegate = self;
    self.MVCollectionView.dataSource = self;
    [self downLoadGiftDataFinished:^{
        [self.MVCollectionView reloadData];
    }];

    
    //注册cell
    [self.MVCollectionView registerNib:[UINib  nibWithNibName:@"MVCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"collectionViewCell"];
    

    
}

#pragma mark - 实现代理方法
//区
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
//展示的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
//内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MVModel  *model = self.dataArray[indexPath.row];
    static NSString *cell_id = @"collectionViewCell";
    
    MVCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cell_id forIndexPath:indexPath];
    
    
    //NSLog(@"%@", self.dataArray);
    [cell setCellDataWithModel:model];
    
    
    //    return (MVCollectionViewCell *)cell;
    return cell;
    
    
    
}
//item的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
  

    CGSize size = CGSizeMake(180, 180);
    return size;
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(15, 15, 15, 15);
}

#pragma mark - 数据请求
-(void)downLoadGiftDataFinished:(void(^)())result {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSURL *url = [[NSURL alloc] init];
        url = [NSURL URLWithString:Url];
        
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            
            NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSDictionary *Dict1 = resultDict[@"data"];
            
            NSArray *array = Dict1[@"mvs"];
            
            for (NSDictionary *dict in array) {
                
                NSArray *dictArray = dict[@"artist"];
                NSDictionary *Videodict = dict[@"video"];
                
                MVModel *Model = [[MVModel alloc]init];
                Model.title = dict[@"title"];
                NSString *imageStr = [dict[@"mv_cover"] stringByReplacingOccurrencesOfString:@"_420x280_.webp" withString:@""];
                Model.mv_cover = imageStr;
                
                
                //   NSLog(@"%@",Model.mv_cover);
                
                //                for (NSDictionary *Dict2 in dictArray) {
                Model.artist_name = [dictArray[0] objectForKey:@"artist_name"];
                //                }
                
                //                for (NSDictionary *urlDict in VideoArray) {
                //                    NSLog(@"%@", VideoArray);
                Model.url = Videodict[@"url"];
                self.urlStr = Model.url;
                //                    NSLog(@"===========%@", Model.url);
                //                }
                
                [self.dataArray addObject:Model];
                
                
                // NSLog(@"=========%@",self.dataArray);
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                result();
            });
            
        }];
        
    });
}


#pragma mark - 懒加载
-(MPMoviePlayerViewController *)moviePlayerViewController {
    
    if (!_moviePlayerViewController) {
        _moviePlayerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:self.urlStr]];
        //全屏播放
        _moviePlayerViewController.view.frame = self.view.frame;
        
        _moviePlayerViewController.view.center = CGPointMake(self.view.bounds.size.width/2 , self.view.bounds.size.height/2 );
        //旋转
        //        CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI/2);
        //        [_moviePlayerViewController.view setTransform:transform];
        [self.view addSubview:_moviePlayerViewController.view];
        //        //全屏播放
        _moviePlayerViewController.moviePlayer.scalingMode = MPMovieScalingModeAspectFill;
        [self addNotification];
    }
    return _moviePlayerViewController;
    
}

-(void)mediaPlayerPlaybackFinished:(NSNotification *)notification {
    NSLog(@"播放完成.%li",self.moviePlayerViewController.moviePlayer.playbackState);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [self downLoadGiftDataFinished:^{
        
        [self presentMoviePlayerViewControllerAnimated:self.moviePlayerViewController];
        self.moviePlayerViewController = nil;
    }];
    
}

#pragma mark 控制器通知
//添加通知监控媒体播放控制状态
-(void)addNotification{
    NSNotificationCenter *notificationCenter=[NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayerViewController.moviePlayer];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayerViewController.moviePlayer];
}

/**
 *  播放状态改变,注意播放完成时的状态是暂停
 *
 *  @param notification 通知对象
 */
-(void)mediaPlayerPlaybackStateChange:(NSNotification *)notification {
    
    switch (self.moviePlayerViewController.moviePlayer.playbackState) {
        case MPMoviePlaybackStatePlaying:
            NSLog(@"正在播放");
            break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"暂停播放");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"停止播放");
            break;
        default:
            NSLog(@"播放状态:%li",self.moviePlayerViewController.moviePlayer.playbackState);
            break;
    }
    
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
